# -*- coding: utf-8 -*-

from django.db import models
from django.db.models import QuerySet
from django.utils.translation import ugettext_lazy as _

from common.constant import LEN_SHORT, LEN_NORMAL, EMPTY_STRING


class TimeInfo(models.Model):
    """
    Add time fields to another models.
    """

    class Meta:
        verbose_name = "时间相关字段"
        abstract = True

    created_time = models.DateTimeField("创建时间", auto_now_add=True, db_index=True)
    updated_time = models.DateTimeField("修改时间", auto_now=True)


class MaintainerInfo(models.Model):
    """
    Add maintainer fields to another models.
    """

    class Meta:
        verbose_name = "维护者相关字段"
        abstract = True

    created_by = models.CharField("创建者", max_length=LEN_SHORT, default=EMPTY_STRING)
    updated_by = models.CharField("更新者", max_length=LEN_SHORT, default=EMPTY_STRING)
    created_by_cn = models.CharField("创建者中文名", max_length=LEN_NORMAL, default=EMPTY_STRING)
    updated_by_cn = models.CharField("更新者中文名", max_length=LEN_NORMAL, default=EMPTY_STRING)


class Manager(models.Manager):
    # 支持软删除
    def get_queryset(self):
        return SoftDeleteQuerySet(self.model).filter(is_deleted=False)


class SoftDeleteQuerySet(QuerySet):
    # 支持软删除
    def delete(self):
        return super(SoftDeleteQuerySet, self).update(is_deleted=True)

    def hard_delete(self):
        return super(SoftDeleteQuerySet, self).delete()


class Model(MaintainerInfo, TimeInfo):
    class Meta:
        abstract = True


class SoftDeleteModel(models.Model):
    is_deleted = models.BooleanField(_("是否软删除"), default=False)

    objects = Manager()
    _objects = models.Manager()

    class Meta:
        abstract = True

    def delete(self, using=None, keep_parents=False):
        self.is_deleted = True
        self.save()

    def hard_delete(self, using=None):
        super().delete()
